package com.gitee.zycra.union.api.common.filter;

import com.gitee.zycra.union.api.common.util.TraceIdUtil;
import org.slf4j.MDC;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zycra
 */
@Component
public class TraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
            IOException {
        String traceId = request.getHeader(TraceIdUtil.TRACE_ID);
        if (traceId == null) {
            traceId = TraceIdUtil.getTraceId();
        }
        MDC.put(TraceIdUtil.TRACE_ID, traceId);
        filterChain.doFilter(request, response);
        MDC.remove(TraceIdUtil.TRACE_ID);
    }

    @Bean
    public FilterRegistrationBean<TraceIdFilter> webTraceIdFilter() {
        FilterRegistrationBean<TraceIdFilter> bean = new FilterRegistrationBean<>();
        bean.setOrder(1);
        bean.setFilter(new TraceIdFilter());
        bean.setName("webTraceIdFilter");
        bean.addUrlPatterns("/*");
        return bean;
    }
}
